package wqh.controller.file;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import wqh.domain.User;
import wqh.global.GlobalSession;
import wqh.service.UserService;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;

/**
 * Created by devts on 2016/11/14.
 */
@Controller
@CrossOrigin(origins = "*")
@RequestMapping("/user_file")
public class UserPicture {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/getPicture",method = RequestMethod.GET,produces = MediaType.IMAGE_JPEG_VALUE)
    public ResponseEntity<byte[]> userGetPicture(HttpServletRequest httpServletRequest)
    {
        try {
            String userName = GlobalSession.getUserNameBySessionID(httpServletRequest.getSession().getId());
            User find = new User();
            find.setUser(userName);
            List<User> userList = userService.findAllByObject(find);
            if(userList.size() == 0) return null;
            String serverPath = httpServletRequest.getServletContext().getRealPath("/");
            File file = new File(serverPath + userList.get(0).getPicture());
            if(!file.exists()) file = new File(serverPath + "\\WEB-INF\\ftl\\assets\\img\\error.jpg");
            HttpHeaders httpHeaders = new HttpHeaders();
            String fileName = file.getName();
            httpHeaders.setContentDispositionFormData("attachment",java.net.URLEncoder.encode(fileName,"UTF-8"));
            httpHeaders.setContentType(MediaType.IMAGE_JPEG);
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),httpHeaders, HttpStatus.CREATED);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }

}
